#!/usr/bin/env python
# coding: utf-8

# In[1]:

import sys # 用于传参
import math
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
# windows系统使用
plt.rcParams['font.sans-serif'] = ['SimHei']
# mac系统使用
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# plt.rcParams['axes.unicode_minus'] = False

# In[2]:

def category(data):
    for i in range(0,data.shape[1],1):
        if(np.issubdtype(data[data.columns[i]],"object")):
             data[data.columns[i]] = data[data.columns[i]].astype('category').cat.codes


# In[3]:


def preprocessor(inputDataSet, usingModel, outputDataSet, outputDeviation):

    data = pd.read_csv(inputDataSet,index_col="检测时间",parse_dates=True)
    data_time = pd.read_csv(inputDataSet,parse_dates=True)
    data_time = data_time[(data_time['设备名称']=='2号主变35KV套管接线夹B相')]
    time_list = data_time["检测时间"]
    time_list = time_list.values
    print(data_time)
    data = data[(data['设备名称']=='2号主变35KV套管接线夹B相')]
    data = data[[ '设备温度(℃)', '环境温度(℃)', '环境湿度', '风速(m/s)', '风向', '负载电流(A)']]
    category(data)
    print('*********************************')
    data.sort_index(inplace=True)
    print(data)
    # print(data.shape)


    sequence_length = 24
    delay = 0
    data_ = []
    for i in range(len(data) - sequence_length - delay):
        data_.append(data.iloc[i: i + sequence_length + delay])
    data_ = np.array([df.values for df in data_])
    X = data_[:, 0:-delay, :]
    Y = data_[:, -delay:,0]


#     X_data = data[['设备温度(℃)', '环境温度(℃)', '环境湿度', '风速(m/s)', '风向', '负载电流(A)']]
#     Y_data = data[['设备温度(℃)', ]]
#     # print(X_data.shape, Y_data.shape)
#     X = np.zeros((X_data.shape[0] // 24,
#                       24,
#                       X_data.shape[-1]))
#     Y = np.zeros((Y_data.shape[0] // 24,
#                       6))
#     rows = range(0, X_data.shape[0] - 29, 24)
#     for i, row in enumerate(rows):
#         X[i, :, :] = X_data.iloc[row: row + 24]
#         Y[i, :] = [Y_data.iloc[row + 24], Y_data.iloc[row + 24 + 1], Y_data.iloc[row + 24 + 2],
#                     Y_data.iloc[row + 24 + 3], Y_data.iloc[row + 24 + 4], Y_data.iloc[row + 24 + 5]]

    X_train = X[:int(X.shape[0] * 0.7)]
    Y_train = Y[:int(Y.shape[0] * 0.7)]
    X_val = X[int(X.shape[0] * 0.7)::]
    Y_val = Y[int(Y.shape[0] * 0.7)::]

    print(len(data_time))
    print("****")
    print(len(Y_val))
    time_list = time_list[len(data_time)-len(Y_val):]
    print(time_list)


    X_mean = X_train.mean(axis=0)
    X_std = X_train.std(axis=0)
    Y_mean = Y_train.mean(axis=0)
    Y_std = Y_train.std(axis=0)
#     X_train_norm = (X_train - X_mean) / X_std
#     Y_train_norm = (Y_train - Y_mean) / Y_std
    X_val_norm = (X_val - X_mean) / X_std

    # print(X_train_norm.shape)
    # print(Y_std.shape)

    model = tf.keras.models.load_model(usingModel) # 模型加载

    model_pred = model.predict(X_val_norm,verbose=0)
    val_pred = model_pred * Y_std + Y_mean

    data = pd.DataFrame(np.zeros((6, 2)))
    data.index = ["未来一小时","未来两小时","未来三小时","未来四小时","未来五小时","未来六小时"]

    data.columns = ["MAE(平均绝对误差)", "RMSE(均方根误差)"]
    data.iloc[0,0] = mean_absolute_error(Y_val[:,0],val_pred[:,0])
    data.iloc[0,1] = math.sqrt(mean_squared_error(Y_val[:,0],val_pred[:,0]))
    data.iloc[1,0] = mean_absolute_error(Y_val[:,1],val_pred[:,1])
    data.iloc[1,1] = math.sqrt(mean_squared_error(Y_val[:,1],val_pred[:,1]))
    data.iloc[2,0] = mean_absolute_error(Y_val[:,2],val_pred[:,2])
    data.iloc[2,1] = math.sqrt(mean_squared_error(Y_val[:,2],val_pred[:,2]))
    data.iloc[3,0] = mean_absolute_error(Y_val[:,3],val_pred[:,3])
    data.iloc[3,1] = math.sqrt(mean_squared_error(Y_val[:,3],val_pred[:,3]))
    data.iloc[4,0] = mean_absolute_error(Y_val[:,4],val_pred[:,4])
    data.iloc[4,1] = math.sqrt(mean_squared_error(Y_val[:,4],val_pred[:,4]))
    data.iloc[5,0] = mean_absolute_error(Y_val[:,5],val_pred[:,5])
    data.iloc[5,1] = math.sqrt(mean_squared_error(Y_val[:,5],val_pred[:,5]))






    data.to_csv(outputDeviation,encoding="utf_8_sig",index=True)
    #修改
    result = pd.concat([pd.DataFrame(val_pred),pd.DataFrame(Y_val),pd.DataFrame(time_list)], axis=1)
    result.to_csv(outputDataSet,encoding="utf_8_sig",index=True)

#     plt.figure(figsize=(20,8))
#     plt.plot(Y_val[:,0],label="设备温度预测值")
#     plt.plot(val_pred[:,0],label="设备温度预测值")
#     plt.xlabel("未来小时数")
#     plt.ylabel("设备温度值")
#     plt.title("未来1小时设备温度预测值示意图",fontsize=20)
#     plt.legend()

# #     $不要动，路径从D开始修改！！！！
#     fname = "$$$$$$$$$$D:\\data\\power\\photo\\GRU112.png"
#     print(fname)
#     plt.savefig(fname=fname[len("$$$$$$$$$$"):],figsize=[10,10],dpi=600)

if __name__ == '__main__':
    argvLen = len(sys.argv)
    if(argvLen != 5):
        print("PredictModel.py need 3 argvs, please check your input!")
    else:
        # 接收参数从sys.argv[1]开始，sys.argv[0]是python脚本的参数地址
        inputDataSet = sys.argv[1]
        usingModel = sys.argv[2]
        outputDataSet = sys.argv[3]
        outputDeviation = sys.argv[4]

        # preprocessor("/Users/mylovin/Downloads/repository/NJUPT/IdeaProjects/power/power-bus/target/classes/test5.csv")
        preprocessor(inputDataSet, usingModel, outputDataSet, outputDeviation)
